package org.linlinjava.litemall.core.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class IPGeolocation {


    public static String getIPGeolocation(String ipAddress){
        try {
            URL url = new URL("http://ip-api.com/json/" + ipAddress);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();
                // 解析JSON响应数据
                // 根据API返回的数据结构，提取所需的地理位置信息
                // 这里只是示例，请根据实际响应数据进行解析
                // 解析JSON响应数据
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonResponse = mapper.readTree(response.toString());

                String country = jsonResponse.has("country") ? jsonResponse.get("country").asText() : "";
                String region = jsonResponse.has("regionName") ? jsonResponse.get("regionName").asText() : "";
                String city = jsonResponse.has("city") ? jsonResponse.get("city").asText() : "";
                String isp = jsonResponse.has("isp") ? jsonResponse.get("isp").asText() : "";
                return "国家: "+country+"-地区/省份: "+region+"-城市: "+city+"网络服务提供商: " +isp;
            } else {
                return "ip位置获取失败";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ip位置获取失败";
    }

}
